package cn.haocxy.jfm.gui.dialog;

import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;

/**
 * <p>对话框
 * 
 * <p>对话框用于向用户提供一些重要信息或向用户搜集重要信息.
 * <p>打开的对话框会阻断所有从属窗口的GUI事件,知道用户关闭这个对话框.
 * 
 * <p>对话框包含一个按钮区域,在右下方,其中有若干个按钮,按钮的具体个数,外观,以及功能由子类决定.
 * <p>对话框还包含一个完全由子类定义的内容区域,子类确定它的外表以及功能.
 * 
 * @author 蔡心宇
 *
 */
public abstract class Dialog {
	
	private final Stage stage = new Stage();
	
	private final AnchorPane root = new AnchorPane();
	
	private final AnchorPane contentArea = new AnchorPane();
	
	private final HBox buttons = new HBox();
	
	private final Text info = new Text();
	
	public Dialog() {
		stage.setResizable(false);
		
		stage.setWidth(400);
		stage.setHeight(150);
		
		stage.initModality(Modality.WINDOW_MODAL);
		
		stage.setScene(new Scene(root));
		
		root.getChildren().add(contentArea);
		AnchorPane.setTopAnchor(contentArea, 0.0);
		AnchorPane.setBottomAnchor(contentArea, 50.0);
		AnchorPane.setLeftAnchor(contentArea, 0.0);
		AnchorPane.setRightAnchor(contentArea, 0.0);
		
		info.setTextAlignment(TextAlignment.RIGHT);
		root.getChildren().add(info);
		AnchorPane.setRightAnchor(info, 10.0);
		AnchorPane.setBottomAnchor(info, 40.0);
		
		root.getChildren().add(buttons);
		AnchorPane.setBottomAnchor(buttons, 0.0);
		AnchorPane.setRightAnchor(buttons, 0.0);
		buttons.setPadding(new Insets(10.0));
		buttons.setSpacing(10.0);
		
		setContentArea(contentArea);
		setButtons();
		
		stage.setOnShowing(e->onShowing());
		stage.setOnHiding(e->onHiding());
	}
	
	public final Dialog setTitle(String title) {
		stage.setTitle(title);
		return this;
	}
	
	public final Dialog setInfo(Color color, String info) {
		this.info.setText(info);
		this.info.setFill(color);
		return this;
	}
	
	/**
	 * 打开对话框
	 * 阻断所有从属窗口的事件
	 * 
	 * @param owner 从属窗口
	 * @return 这个对话框本身
	 */
	public final Dialog show(Window owner) {
		stage.initOwner(owner);
		stage.showAndWait();
		return this;
	}
	
	public final Dialog hide() {
		stage.hide();
		return this;
	}
	
	public final Dialog setWidth(double width) {
		stage.setWidth(width);
		return this;
	}
	
	public final Dialog setHeight(double height) {
		stage.setHeight(height);
		return this;
	}
	
	protected final Dialog add(Button button) {
		buttons.getChildren().add(button);
		return this;
	}
	
	protected abstract void setContentArea(AnchorPane pane);
	
	protected abstract void setButtons();
	
	protected abstract void onShowing();
	
	protected abstract void onHiding();
}
